package com.pocket.insight.base.sql.context;

import com.alibaba.fastjson.JSON;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import com.pocket.insight.base.sql.constant.ConnectionConst;
import com.pocket.insight.base.dto.JDBCConfigDto;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

/**
 * 描述：
 *
 * @author shuize
 * @create 2024/11/29
 */
public class JDBCConfigContext {

    private static final String VERSION = "version";

    private static Map<String, JDBCConfigDto> MAP = new HashMap<>();
    private static Map<String, JDBCConfigDto.JDBCVersionDto> VERSION_MAP = new HashMap<>();

    /**
     * 根据外置的配置jdbcConfig添加配置项
     */
    public static void init(String config) {
        if (StringUtils.isNotBlank(config)) {
            List<JDBCConfigDto> configList = JSON.parseArray(config, JDBCConfigDto.class);
            if (CollectionUtils.isNotEmpty(configList)){
                configList.forEach(dto -> {
                    MAP.put(dto.getName(), dto);
                    dto.getVersions().forEach(version -> {
                        VERSION_MAP.put(buildVersionKey(dto.getName()), version);
                    });
                });
            }
        }
    }

    public static JDBCConfigDto.JDBCVersionDto getVersion(String key) {
        return VERSION_MAP.get(buildVersionKey(key));
    }

    public static String buildVersionKey(String name){
        return name + "_" + VERSION;
    }

    public static Properties removeInnerProperties(Properties properties) {
        if (properties == null || properties.size() == 0) {
            return properties;
        }
        Properties jdbcProperties = new Properties();
        for (Map.Entry<Object, Object> entry : properties.entrySet()) {
            String key = (String)entry.getKey();
            if (!StringUtils.startsWith(key, ConnectionConst.PROPERTY_KEY_PREFIX)) {
                jdbcProperties.put(entry.getKey(), entry.getValue());
            }
        }
        return jdbcProperties;
    }

    public static boolean needCustomDatasource(Properties properties) {
        boolean b = false;
        if (properties != null && StringUtils.isNotBlank(properties.getProperty(ConnectionConst.JDBC_JAR_PATH)) && StringUtils.isNotBlank(properties.getProperty(ConnectionConst.JDBC_DRIVER_NAME))) {
            b = true;
        }
        return b;
    }

    public static boolean supportSetAutoCommit(Properties properties) {
        boolean b = true;
        if (properties == null) {
            return true;
        }
        Boolean property = (Boolean)properties.get(ConnectionConst.SET_AUTO_COMMIT);
        if (BooleanUtils.isFalse(property)) {
            b = false;
        }
        return b;
    }

}
